package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
     @Reference
     private SetmealService setmealService;
     @Autowired
     private JedisPool jedisPool;
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile multipartFile){
        String originalFilename = multipartFile.getOriginalFilename();//获取文件名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf(".") - 1);//获取后缀名
        String s = UUID.randomUUID().toString() + suffixName;//随机生成uuid与后缀名向结合，作为新上传图片的名字
        System.out.println(s);
        try {
            QiniuUtils.upload2Qiniu(multipartFile.getBytes(),s);
            //将上传到七牛云的图片存到redis，名字为SETMEAL_PIC_RESOURCES，值为 图片名称
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,s);
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,s);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL,null);
        }
    }
    //增加功能
    @RequestMapping("/add")
    public Result add(int[] checkgroupIds,@RequestBody Setmeal setmeal){
        System.out.println(setmeal.getName());
        try {
            setmealService.add(checkgroupIds,setmeal);
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
    }
    @RequestMapping("/findByPage")
    public PageResult add(@RequestBody QueryPageBean queryPageBean){
        return setmealService.findByPage(queryPageBean);
    }
    @RequestMapping("/findById")
    public Result findById(int id){
        Setmeal byId = setmealService.findById(id);
        return new Result(true,null,byId);
    }

}
